import Vue from 'vue'
import VueRouter from 'vue-router'

import store from "@/store"

import {getNav} from "@/api/sys/menu";

Vue.use(VueRouter)

const routes = [
    {
        path: "/",
        name: "Home",
        component: () => import('@/layout/Layout'),
        children: [
            {
                path: '/index',
                name: 'index',
                meta: {
                    title: "首页"
                },
                component: () => import('@/views/Index/index')
            },
            {
                path: '/profile',
                name: 'Profile',
                meta: {
                    title: "个人中心"
                },
                component: () => import("@/views/Profile/index")
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import("@/views/Login")
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    let hasRoute = store.state.menus.hasRoute
    let token = localStorage.getItem("token")
    if (to.path === '/login') {
        localStorage.removeItem("token")
        next()
    } else if (!token) {
        next({path: '/login'})
    } else if (to.path === '/' || to.path === '') {
        next({path: '/index'});
    } else if (token && !hasRoute) {
        getNav().then(response => {
            //获取当前路由信息
            let newRoutes = router.options.routes;
            // console.log(response)
            const res = JSON.parse(JSON.stringify(response))
            store.commit("setMenuList", res.data.nav)
            store.commit("setPermList", res.data.authority)

            res.data.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {
                        let route = menuToRoute(e)
                        if (route) {
                            newRoutes[0].children.push(route)
                        }
                    })
                }
            })
            router.matcher = new VueRouter({
                mode: 'history',
                base: process.env.BASE_URL,
                routes: newRoutes
            }).matcher
            store.commit("changeRouteStatus", true)
            next({path: to.path})
        })
    } else {
        next()
    }

})

//将信息添加到路由中
const menuToRoute = (menus) => {
    if (!menus.component) {
        return null
    }
    // 复制属性
    let route = {
        path: menus.path,
        name: menus.name,
        meta: {
            icon: menus.icon,
            title: menus.title
        },
        component: () => import('@/views/' + menus.component)
    }

    return route
}

export default router
